package com.sqx.modules.app.controller.app;


import com.aliyun.dyplsapi20170525.models.BindAxnResponse;
import com.aliyun.dyplsapi20170525.models.BindAxnResponseBody;
import com.aliyun.dyplsapi20170525.models.UpdateSubscriptionResponse;
import com.aliyun.dyplsapi20170525.models.UpdateSubscriptionResponseBody;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.AppService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.timedtask.service.RiderLocationService;
import com.sqx.modules.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app/user")
@Api(value = "APP管理", tags = {"APP管理"})
public class AppController {

    @Autowired
    private UserService userService;
    @Autowired
    private AppService appService;
    @Autowired
    private RiderLocationService riderLocationService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private CommonInfoService commonInfoService;

    @Login
    @ApiOperation("生成虚拟号码")
    @GetMapping("/insertVirtualPhone")
    public Result insertVirtualPhone(String phoneA, String phoneB) {
        MessageInfo messageInfo1 = messageInfoDao.selectOne(new QueryWrapper<MessageInfo>().eq("user_name", phoneA).eq("by_user_name", phoneB));
        if (messageInfo1 == null) {
            messageInfo1 = messageInfoDao.selectOne(new QueryWrapper<MessageInfo>().eq("user_name", phoneB).eq("by_user_name", phoneA));
        }
        String accessKeyId = commonInfoService.findOne(386).getValue();
        String accessKeySecret = commonInfoService.findOne(387).getValue();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dyplsapi.aliyuncs.com";
        try {
            String poolKey = commonInfoService.findOne(382).getValue();
            com.aliyun.dyplsapi20170525.Client client = new com.aliyun.dyplsapi20170525.Client(config);
            if (messageInfo1 != null) {
                com.aliyun.dyplsapi20170525.models.UpdateSubscriptionRequest updateSubscriptionRequest = new com.aliyun.dyplsapi20170525.models.UpdateSubscriptionRequest();
                com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
                updateSubscriptionRequest.setPoolKey(poolKey);
                updateSubscriptionRequest.setSubsId(messageInfo1.getTitle());
                updateSubscriptionRequest.setPhoneNoX(messageInfo1.getContent());
                String value = commonInfoService.findOne(418).getValue();
                if("是".equals(value)){
                    updateSubscriptionRequest.setIsRecordingEnabled(true);
                }
                Calendar calendar=Calendar.getInstance();
                calendar.add(Calendar.HOUR,1);
                updateSubscriptionRequest.setExpiration(DateUtils.format(calendar.getTime()));
                updateSubscriptionRequest.setOperateType("updateExpire");
                UpdateSubscriptionResponse updateSubscriptionResponse = client.updateSubscriptionWithOptions(updateSubscriptionRequest, runtime);
                UpdateSubscriptionResponseBody body = updateSubscriptionResponse.getBody();
                String code = body.getCode();
                if("OK".equals(code)){
                    return Result.success().put("data", messageInfo1.getContent());
                }
                messageInfoDao.deleteById(messageInfo1.getId());
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState("18");
            messageInfo.setUserName(phoneA);
            messageInfo.setByUserName(phoneB);
            com.aliyun.dyplsapi20170525.models.BindAxnRequest bindAxnRequest = new com.aliyun.dyplsapi20170525.models.BindAxnRequest();
            bindAxnRequest.setPoolKey(poolKey);
            bindAxnRequest.setPhoneNoA(phoneA);
            bindAxnRequest.setPhoneNoB(phoneB);
            String value = commonInfoService.findOne(418).getValue();
            if("是".equals(value)){
                bindAxnRequest.setIsRecordingEnabled(true);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR, 1);
            bindAxnRequest.setExpiration(DateUtils.format(calendar.getTime()));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            BindAxnResponse bindAxnResponse = client.bindAxnWithOptions(bindAxnRequest, runtime);
            BindAxnResponseBody body = bindAxnResponse.getBody();
            String code = body.code;
            if (!"OK".equals(code)) {
                return Result.error("获取号码失败！" + body.getMessage());
            }
            BindAxnResponseBody.BindAxnResponseBodySecretBindDTO secretBindDTO = body.getSecretBindDTO();
            messageInfo.setContent(secretBindDTO.getSecretNo());
            messageInfo.setTitle(secretBindDTO.getSubsId());
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageInfoDao.insert(messageInfo);
            return Result.success().put("data", secretBindDTO.getSecretNo());
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return Result.error("获取号码失败！");
    }

    @Login
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("用户端修改密码")
    public Result updatePwd(@LoginUser UserEntity user, String pwd, String oldPwd) {
        if (!user.getPassword().equals(DigestUtils.sha256Hex(oldPwd))) {
            return Result.error("原始密码不正确！");
        }
        if (pwd.equals(oldPwd)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        user.setPassword(DigestUtils.sha256Hex(pwd));
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
    @ApiOperation("用户端换绑手机号")
    @ResponseBody
    public Result updatePhone(@RequestAttribute("userId") Long userId, @RequestParam String phone, @RequestParam String msg) {
        return userService.updatePhone(phone, msg, userId);
    }

    @Login
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ApiOperation("用户修改个人信息")
    @ResponseBody
    public Result updateUser(@RequestBody UserEntity userEntity, @RequestAttribute("userId") Long userId) {
        userEntity.setUserId(userId);
        userService.updateById(userEntity);
        return Result.success();
    }



    @Login
    @RequestMapping(value = "/updateUserImageUrl", method = RequestMethod.POST)
    @ApiOperation("用户修改头像")
    @ResponseBody
    public Result updateUserImageUrl(@LoginUser UserEntity user, String avatar) {
        user.setAvatar(avatar);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/updateUserName", method = RequestMethod.POST)
    @ApiOperation("用户修改昵称")
    @ResponseBody
    public Result updateUserName(@LoginUser UserEntity user, String userName) {
        user.setNickName(userName);
        userService.updateById(user);
        return Result.success();
    }

    @Login
    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@LoginUser UserEntity user) {
        return Result.success().put("data", user);
    }

    @RequestMapping(value = "/selectUserDetails", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserDetails(Long userId) {
        return Result.success().put("data", userService.selectUserById(userId));
    }


    @RequestMapping(value = "/selectNewApp", method = RequestMethod.GET)
    @ApiOperation("升级检测")
    @ResponseBody
    public Result selectNewApp() {
        return Result.success().put("data", appService.selectNewApp());
    }

    @RequestMapping(value = "/updateClientId", method = RequestMethod.GET)
    @ApiOperation("绑定ClientId")
    @ResponseBody
    public Result updateClientId(String clientId, Long userId, Integer sysPhone) {
        UserEntity userEntity = new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientid(clientId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateClientRiderId", method = RequestMethod.GET)
    @ApiOperation("绑定师傅ClientId")
    @ResponseBody
    public Result updateClientRiderId(String clientRiderId, Long userId, Integer sysPhone) {
        UserEntity userEntity = new UserEntity();
        userEntity.setSysPhone(sysPhone);
        userEntity.setUserId(userId);
        userEntity.setClientRiderId(clientRiderId);
        userService.updateById(userEntity);
        return Result.success();
    }

    @Login
    @GetMapping("/queryInviterCount")
    public Result select(@LoginUser UserEntity userEntity) {
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        return Result.success().put("data", count);
    }

    /**
     * (师傅端)获取附近司机
     * @return
     */
    @Login
    @GetMapping("getRiderCount")
    public Result getRiderCount(@RequestAttribute("userId") Long userId, String city, Double lng, Double lat) {
        return Result.success().put("data", riderLocationService.getRiderCount(userId, city, lng, lat));
    }
}
